/**
 * Sangame.com Inc.
 * Copyright (c) 2006-2011 All Rights Reserved.
 */
package com.nmp.web.controller.taobao;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.nmp.service.base.result.Result;
import com.nmp.service.base.result.ResultCode;
import com.nmp.service.taobao.TaobaoUserService;
import com.nmp.web.controller.base.ControllerSupport;

/**
 * 淘宝用户操作
 * @author defier.lai
 * 2011-11-23 上午01:52:57
 * @version 1.0
 */
@Controller
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@RequestMapping("/taobao")
public class TaobaoUserController extends ControllerSupport {
	
	private final static Logger LOG	= LoggerFactory.getLogger(TaobaoUserController.class);
	
	@Resource
	private TaobaoUserService taobaoUserService;

	/**
	 * 淘宝用户授权
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/user/connect")
    public void connect(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Result result = taobaoUserService.getAccountAuthorizeUrl();
		if(result.getResultCode().getCode() == ResultCode.SUCCESS) {
			String authorizeUrl = (String)result.getDefaultModel();
			response.sendRedirect(authorizeUrl);
		} else {
			LOG.error("connect is error! code:{}, message:{}", result.getResultCode().getCode(), result.getResultCode().getMessage());
		}
    }
	
	/**
	 * 淘宝授权回调地址
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/user/callback")
    public ModelAndView callback(@RequestParam("code") String code) {
		Result result = taobaoUserService.bindTaobaoToken(code);
		if(result.getResultCode().getCode() == ResultCode.SUCCESS) {
			getPopMessage().setStatus(true);
			getPopMessage().setMessage("绑定淘宝帐户成功！");
		} else {
			getPopMessage().setStatus(false);
			getPopMessage().setMessage("绑定淘宝帐户失败！");
		}
    	return getModelAndView("callback");
    }
	
	@Override
	public String getParentPath() {
		return "/taobao/user";
	}

}
